package team.first.movieapiv2pro.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import team.first.movieapiv2pro.dao.AuthorizationDAO;
import team.first.movieapiv2pro.dao.CommentDAO;
import team.first.movieapiv2pro.doc.CommentDoc;
import team.first.movieapiv2pro.domain.Comment;
import team.first.movieapiv2pro.domain.User;
import team.first.movieapiv2pro.service.CommentService;
import team.first.movieapiv2pro.vo.ResponseComment;

import java.time.Duration;
import java.util.List;

/**
 * @Author: HAPPY
 * @Project_name: project
 * @Package_name: team.first.movieapiv2pro.dao.impl
 * @Date: 2021/12/26 9:34
 * @Description:
 */
@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private CommentDAO commentDAO;
    @Autowired
    private AuthorizationDAO authorizationDAO;

    @Override
    public List<ResponseComment> findMovieComment(Integer movieId) {
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();

        String commentCache = operations.get("movie-api-v2:data:comment:" + movieId);
        List<ResponseComment> commentList = null;
        if (commentCache != null) {
            commentList = JSON.parseArray(commentCache, ResponseComment.class);
        } else {
            commentList = BeanUtil.copyToList(commentDAO.selectMovieComment(movieId), ResponseComment.class);
            // 做缓存
            operations.set("movie-api-v2:data:comment:" + movieId, JSON.toJSONString(commentList), Duration.ofSeconds(60 * 10));
        }
        return commentList;
    }

    @Override
    public boolean saveComment(Comment comment) {
        CommentDoc commentDoc = new CommentDoc();
        BeanUtil.copyProperties(comment, commentDoc);

        // 获取用户信息
        User user = authorizationDAO.selectById(comment.getUserId());

        commentDoc.setNickname(user.getNickname());
        commentDoc.setAvatar(user.getAvatar());
        boolean res =  commentDAO.insertComment(commentDoc);
        // 清空缓存，下次重新刷新缓存
        stringRedisTemplate.opsForValue().set("movie-api-v2:data:comment:" + comment.getMovieId(), "", Duration.ofSeconds(1));
        return res;
    }
}
